package com.whx.authorization.api;

import com.alibaba.fastjson.JSON;
import com.whx.authorization.request.BaseRequest;
import com.whx.authorization.response.BaseResponse;
import com.whx.authorization.util.SimpleHttpUtil;
import org.jsoup.Connection;

import java.io.IOException;

/**
 * 类名：AuthorizationClient
 * 类路径： com.whx.authorization.api.AuthorizationClient
 * 创建者： whx
 * 创建时间： 10/8/18 9:49 AM
 * 项目： authorization_center
 * 描述：
 */
public class AuthorizationClient {

    private String authorizationServerUrl;

    public <T extends BaseResponse> T execute(BaseRequest<T> request) {
        T resp = null;
        if (request != null) {
            request.prepareRequest();
            try {
                Connection.Response result = SimpleHttpUtil.execute(requestUrl(request.getMethodPath()), request.getParamMap(), request.getHeaderMap(),
                        request.getCookieMap(), request.getHttpMethod());
                resp = JSON.parseObject(result.body(), request.getResponseClass());
            } catch (IOException e) {
                try {
                    resp = request.getResponseClass().newInstance();
                    resp.setSuccess(false);
                    resp.setErrorCode("FAIL TO INVOKE AUTHORIZATION");
                    return resp;
                } catch (InstantiationException e1) {
                } catch (IllegalAccessException e1) {
                }
            }
        }
        return resp;
    }

    private String requestUrl(String path) {
        return authorizationServerUrl.endsWith("/")?authorizationServerUrl.concat(path):authorizationServerUrl.concat("/").concat(path);
    }

    public String getAuthorizationServerUrl() {
        return authorizationServerUrl;
    }

    public void setAuthorizationServerUrl(String authorizationServerUrl) {
        this.authorizationServerUrl = authorizationServerUrl;
    }
}
